<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="活动标题" prop="title">
        <el-input
            v-model="queryParams.title"
            placeholder="请输入活动标题"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="活动类型" prop="playType">
        <el-select v-model="queryParams.playType" placeholder="请选择活动类型" clearable>
          <el-option
              v-for="dict in ty_play_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="playStartTime">
        <el-date-picker clearable
                        v-model="queryParams.playStartTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="playEndTime">
        <el-date-picker clearable
                        v-model="queryParams.playEndTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="活动人数" prop="playNum">
        <el-input-number
            :controls="false"
            :precision="0"
            :min="0"
            v-model="queryParams.playNum"
            placeholder="请输入活动人数"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否收费" prop="isFee">
        <el-select v-model="queryParams.isFee" placeholder="请选择是否收费" clearable>
          <el-option
              v-for="dict in is_free"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="useUserStore().userType === '0'">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['ty:tyPlay:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5" v-if="useUserStore().userType === '0'">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['ty:tyPlay:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5" v-if="useUserStore().userType === '0'">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['ty:tyPlay:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['ty:tyPlay:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tyPlayList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="活动标题" width="200" align="center" prop="title"/>
      <el-table-column label="活动类型" width="80" align="center" prop="playType">
        <template #default="scope">
          <dict-tag :options="ty_play_type" :value="scope.row.playType"/>
        </template>
      </el-table-column>
      <el-table-column label="活动时间" align="center" prop="playStartTime" width="180">
        <template #default="scope">
          <span>{{
              parseTime(scope.row.playStartTime, '{y}-{m}-{d}')
            }}-{{ parseTime(scope.row.playEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动人数" width="80" align="center" prop="playNum"/>
      <el-table-column label="运动类型" width="100" align="center" prop="sportType"/>
      <el-table-column label="是否收费" width="80" align="center" prop="isFee">
        <template #default="scope">
          <dict-tag :options="is_free" :value="scope.row.isFee"/>
        </template>
      </el-table-column>
      <el-table-column label="是否发布" width="100" align="center" prop="isPush">
        <template #default="scope">
          <div class="padRight" @click="handleIsPushChange(scope.row)">
            <el-switch
                v-model="scope.row.isPush"
                active-value="Y"
                inactive-value="N"
            ></el-switch>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="活动费用" width="80" align="center" prop="fee"/>
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     :class="{'but-disabled': !((scope.row.playType === 1 && scope.row.isPush === 'N') || (scope.row.playType === 2 && useUserStore().userId===1))}"
                     v-hasPermi="['ty:tyPlay:edit']">
            修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     :class="{'but-disabled': !((scope.row.playType === 1 && scope.row.isPush === 'N') || (scope.row.playType === 2 && useUserStore().userId===1))}"
                     v-hasPermi="['ty:tyPlay:remove']">删除
          </el-button>
          <el-button link type="primary" icon="Money" @click="handlePackage(scope.row)">活动套餐</el-button>
<!--          <el-button link type="primary" icon="Money" @click="handleEvaluation(scope.row)">评价列表</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改活动项目对话框 -->
    <el-dialog :title="dialogTitle" v-model="open" width="1000px" append-to-body>
      <!--  @close="closeDialog" -->
      <el-form ref="tyPlayRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="活动标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入活动标题"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="主图" prop="mainPic">
              <image-upload :limit="1" v-model="form.mainPic"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详情图" prop="detailPic">
<!--              <image-upload :limit="10" v-model="form.detailPic"/>-->
              <video-orimage-upload :limit="10" v-model="form.detailPic"></video-orimage-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="群聊码" prop="groupPic">
              <image-upload :limit="1" v-model="form.groupPic"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="省市" prop="cityCode">
              <el-cascader-city v-model="form.cityCode" :is-save="true"></el-cascader-city>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="活动类型" prop="playType">-->
          <!--              <el-select v-model="form.playType" placeholder="请选择活动类型">-->
          <!--                <el-option-->
          <!--                    v-for="dict in ty_play_type"-->
          <!--                    :key="dict.value"-->
          <!--                    :label="dict.label"-->
          <!--                    :value="parseInt(dict.value)"-->
          <!--                ></el-option>-->
          <!--              </el-select>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动时间" prop="playStartTime">
              <el-date-picker
                  clearable
                  v-model="playTimeRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD HH:mm"
                  @change="handlePlayTimeChange"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="playType == 1 ||dialogTitle =='添加活动项目'">
            <el-form-item label="报名时间" prop="playSignStart">
              <el-date-picker
                  clearable
                  v-model="playSignTimeRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD HH:mm"
                  @change="handleSignTimeRangeChange"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
        </el-row>
        <el-row>
          <el-col :span="12" v-show="playType == 1 ||dialogTitle =='添加活动项目'">
            <el-form-item label="活动人数" prop="playNum">
              <el-input-number :controls="false" v-model="form.playNum" placeholder="请输入活动人数" min="1" max="999"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运动类型" prop="sportType">
              <el-select v-model="form.sportType" placeholder="请选择运动类型">
                <el-option
                    v-for="dict in sport_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否收费" prop="isFee">
              <el-radio-group v-model="form.isFee">
                <el-radio
                    v-for="dict in is_free"
                    :key="dict.value"
                    :label="parseInt(dict.value)"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动费用" prop="fee" v-if="form.isFee === 1">
              <el-input-number :controls="false" min="0" v-model="form.fee"  :precision="2" placeholder="请输入活动费用"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="活动地址" prop="playAddress">
              <el-input v-model="form.playAddress" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <map-component :key="mapComponentKey"
                :longitude="form.lon" :latitude="form.lat" @coordinateClicked="handleCoordinateClicked"
            ></map-component>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="活动描述" prop="playDesc">
              <editor v-model="form.playDesc" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24" v-show="playType == 1 ||dialogTitle =='添加活动项目'">
            <el-form-item label="注意事项" prop="attention">
              <editor v-model="form.attention" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TyPlay">
import {listTyPlay, getTyPlay, delTyPlay, addTyPlay, updateTyPlay,changeIsPush} from "@/api/ty/tyPlay";
import router from "@/router";
import useUserStore from "@/store/modules/user";
import {onBeforeUnmount, watch,ref,reactive} from "vue";
import VideoOrimageUpload from "@/components/VideoOrimageUpload/index.vue";
const {proxy} = getCurrentInstance();
const {is_free, ty_play_type, sport_type} = proxy.useDict('is_free', 'ty_play_type', 'sport_type');

const tyPlayList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dialogTitle = ref("");
const playTimeRange = ref([]);
const playSignTimeRange = ref([]);
const playType = ref("")
const mapComponentKey = ref(0)
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
    playType: null,
    playStartTime: null,
    playEndTime: null,
    playNum: null,
    sportType: null,
    playAddress: null,
    playDesc: null,
    isFee: null,
  },
  rules: {
    title:[
      {required: true, message: "活动标题不能为空", trigger: "blur"},
      {
        min: 0,
        max: 20,
        message: "活动标题长度需要小于20字以内",
        trigger: "blur"
      }
    ],
    mainPic:[
      {required: true, message: "请上传主图", trigger: "blur"}
    ],
    detailPic:[
      {required: true, message: "请上传详情图", trigger: "blur"}
    ],
    packagesTitle: [
      {required: true, message: "套餐标题不能为空", trigger: "blur"}
    ],
    cityCode: [
      {required: true, message: "省市不能为空", trigger: "blur"}
    ],
    playStartTime: [
      {required: true, message: "请选择活动时间", trigger: "blur"}
    ],
    playNum: [
      {required: true, message: "活动人数不能为空", trigger: "blur"}
    ],
    sportType: [
      {required: true, message: "请选择运动类型", trigger: "blur"}
    ],
    isFee: [
      {required: true, message: "请选择是否收费", trigger: "blur"}
    ],
    playAddress :[
      {required: true, message: "请输入活动地址", trigger: "blur"}
    ],
    fee :[
      {required: true, message: "请输入活动费用", trigger: "blur"},
      {
        validator: (rule, value, callback) => {
          if (value > 0) {
            callback(); // 校验通过
          } else {
            callback(new Error("活动费用必须大于0")); // 校验不通过，返回错误信息
          }
        },
        trigger: "blur"
      }
    ],
    playSignStart: [
      {required: true, message: "请选择报名时间", trigger: "blur"},
      {
        validator: validateSignTimeRange,
        trigger: 'change',
        message: "报名时间不能晚于等于活动结束时间"
      }
    ],
    playDesc:[
      {required: true, message: "请输入活动描述", trigger: "blur"}
    ],
    attention:[
      {required: true, message: "请输入注意事项", trigger: "blur"}
    ]
  }
});

const {queryParams,pickerOptions, form, rules} = toRefs(data);

function validateSignTimeRange(rule, value, callback) {
  const playEndTime = playTimeRange.value ? playTimeRange.value[1] : null;
  const signEndTime = playSignTimeRange.value ? playSignTimeRange.value[1] : null;
  if (playEndTime && signEndTime && signEndTime > playEndTime) {
    callback(new Error('报名时间不能晚于活动结束时间'));
  } else {
    callback();
  }
}

/** 查询活动项目列表 */
function getList() {
  loading.value = true;
  listTyPlay(queryParams.value).then(response => {
    tyPlayList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// function closeDialog() {
//   reset();
// }

// 表单重置
function reset() {
  form.value = {
    id: undefined,
    title: undefined,
    mainPic: undefined,
    detailPic: undefined,
    groupPic: undefined,
    playType: undefined,
    playStartTime: undefined,
    playEndTime: undefined,
    playSignStart: undefined,
    playSignEnd: undefined,
    packagesTitle: undefined,
    playNum: undefined,
    sportType: undefined,
    playAddress: undefined,
    playDesc: undefined,
    lat: 31.8639,
    lon: 118.8083,
    isFee: 0,
    attention: undefined,
    fee: undefined,
    isVote: undefined,
    createTime: undefined,
    updateTime: undefined,
    deleted: undefined,
    purchaseLimitTime: undefined,
    comboName: undefined,
    purchaseLimit: undefined,
    limitPrice: undefined,
    cityCode: useUserStore().cityCode
  };
  playTimeRange.value = [];
  playSignTimeRange.value = [];
  mapComponentKey.value += 1;
  proxy.resetForm("tyPlayRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  dialogTitle.value = "添加活动项目";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getTyPlay(_id).then(response => {
    
    form.value = response.data;
    playSignTimeRange.value = [response.data.playSignStart, response.data.playSignEnd];
    playTimeRange.value = [response.data.playStartTime, response.data.playEndTime];
    open.value = true;
    dialogTitle.value = "修改活动项目";

    playType.value = response.data.playType
    
    if(response.data.playType == 2) {
      rules.value.attention[0].required = false
      rules.value.playNum[0].required = false
      rules.value.playSignStart[0].required = false
      rules.value.playSignStart[1] = ''
      
    } else {
      rules.value.attention[0].required = true
      rules.value.playNum[0].required = true
      rules.value.playSignStart[0].required = true
      rules.value.playSignStart[1] = {
        validator: validateSignTimeRange,
        trigger: 'change',
        message: "报名时间不能晚于活动结束时间"
      }
    }
    
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["tyPlayRef"].validate(valid => {
    if (valid) {
      if (form.value.isFee === 0){
        form.value.fee = 0;
      }
      if (form.value.id != null) {
        updateTyPlay(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        //后台创建统一官方活动
        form.value.playType = 1;
        addTyPlay(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除该数据项？').then(function () {
    return delTyPlay(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/tyPlay/export', {
    ...queryParams.value
  }, `tyPlay_${new Date().getTime()}.xlsx`)
}

function handleCoordinateClicked(coordinate) {
  // 更新经纬度
  form.value.lon = coordinate.lng;
  form.value.lat = coordinate.lat;
  form.value.playAddress = coordinate.address;
}

function handlePackage(row) {
  const id = row.id || ids.value[0];
  const packageableType = "Play";
  router.push({
    path: "/play/package/index/" + id,
    query: {
      pageNum: queryParams.value.pageNum,
      packageableType: packageableType,
      playType:row.playType,
      playNum:row.playNum,
      isPush:row.isPush,
      playEndTime:row.playEndTime,
      playSignEnd:row.playSignEnd, //报名结束时间
    }
  });
}

function handlePlayTimeChange(value) {
  if (value && value.length === 2) {
    form.value.playStartTime = value[0];
    form.value.playEndTime = value[1];
  }
}

function handleSignTimeRangeChange(value) {
  if (value && value.length === 2) {
    form.value.playSignStart = value[0];
    form.value.playSignEnd = value[1];
  }
}

/** 活动上下架  */
function handleIsPushChange(row) {
  let text = row.isPush === "N" ? "下架" : "发布";
  proxy.$modal.confirm('确定要将该活动'+text+ '吗').then(function () {
    return changeIsPush(row.id, row.isPush);
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
    getList();
  }).catch(function () {
    getList();
  });
};
function handleEvaluation(row) {
  const id = row.id || ids.value[0];
  const packageableType = "Play";
  router.push({path: "/play/tyEvaluation/index/" + id, query: {pageNum: queryParams.value.pageNum,packageableType:packageableType}});
}
getList();

const stopWatching = watch(() => useUserStore().cascaderKey, (v) => {
  getList();
}, { immediate: true });

onBeforeUnmount(() => {
  stopWatching();
});
</script>
